<template>
  <el-dialog
    :model-value="roleShow"
    title="分配角色"
    @close="emit('roleShowFn')"
  >
    <el-select
      v-model="list"
      multiple
      placeholder="分配角色"
      style="width: 240px"
    >
      <el-option
        v-for="item in roles"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="emit('roleShowFn')">取消</el-button>
        <el-button type="primary" @click="getUserFn">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ElMessage, ElMessageBox } from "element-plus";
import { ref, watch } from "vue";
import { userListAllApi, getUserMenuApi, setUserUpdateApi } from "../api";
const emit = defineEmits(["roleShowFn"]);
const props = defineProps({
  roleShow: {
    type: Boolean,
    default: true,
  },
  id: {
    type: Number,
    default: 0,
  },
});
const getUserFn = () => {
  ElMessageBox.confirm("确定要修改用户角色吗?", "修改用户角色", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true,
  })
    .then(() => {
      setUserUpdateApi(props.id, list.value).then((res) => {
        if (res.code === 200) {
          ElMessage.success("分配成功");
          emit("roleShowFn");
        }
      });
    })
    .catch(() => {});
};
watch(
  () => props.id,
  () => {
    console.log(props.id);
    if (props.id !== 0) {
      getUserMenuApi(props.id).then((res) => {
        console.log(res);
        list.value = res.data.map((item) => item.id);
      });
    }
  }
);

const list = ref<number[]>([]);
const roles = ref<Array<{ value: number; label: string }>>([]);
userListAllApi().then((res) => {
  if (res.code === 200) {
    roles.value = res.data.map((item) => ({
      label: item.name,
      value: item.id,
    }));
  }
});
</script>
<style lang="less" scoped></style>
